
package com.purchase.ml.security;


import com.purchase.ml.bean.SpringContextHolder;
import com.purchase.ml.config.cache.TokenCache;
import com.purchase.ml.entity.acc.SysUser;
import com.purchase.ml.entity.sys.ShiroUser;
import com.purchase.ml.entity.sys.SysRole;
import com.purchase.ml.entity.sys.SysRoleUser;
import com.purchase.ml.enums.ManagerStatusEnum;
import com.purchase.ml.mapper.sys.SysUserMapper;
import com.purchase.ml.mapper.sys.SysRoleMapper;
import com.purchase.ml.mapper.sys.SysRolePermissionMapper;
import com.purchase.ml.mapper.sys.SysRoleUserMapper;
import com.purchase.ml.utils.HttpUtil;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * @description: TODO
 * @author kyyang
 * @date 2020/12/28 20:17
 * @version 1.0
 */

@Service
@DependsOn("springContextHolder")
@Transactional(readOnly = true)
public class ShiroFactroy {


   @Autowired
    private SysUserMapper sysUserMapper;


   @Autowired
   private SysRoleUserMapper sysRoleUserMapper;

   @Autowired
   private SysRoleMapper sysRoleMapper;

   @Autowired
   private SysRolePermissionMapper sysRolePermissionMapper;

   /* @Autowired
    private RoleRepository roleRepository;*/

    @Autowired
    private TokenCache tokenCache;

    public static ShiroFactroy me() {
        return SpringContextHolder.getBean(ShiroFactroy.class);
    }


    public SysUser user(Long id) {

        SysUser user = sysUserMapper.selectById(id);

        // 账号不存在
        if (null == user) {
            throw new CredentialsException();
        }
        // 账号被冻结
        if (user.getState().equals(ManagerStatusEnum.OK.getCode())) {
            throw new LockedAccountException();
        }
        return user;
    }


    public ShiroUser shiroUser(SysUser user) {
        ShiroUser shiroUser = tokenCache.getUser(HttpUtil.getToken());
        if (shiroUser != null) {
            return shiroUser;
        }
        shiroUser = new ShiroUser();
        shiroUser.setId(Long.valueOf(user.getId()));            // 账号id
        shiroUser.setAcc(user.getAcc());// 账号
        shiroUser.setName(user.getName());        // 用户名称
        shiroUser.setPwd(user.getPwd());
       // Long[] roleArray = Convert.toLongArray(",", user.getRoleid());
        List<SysRoleUser> sysRoleUsers = sysRoleUserMapper.selectByUserId(Long.valueOf(user.getId()));
        List<Long> roleList = new ArrayList<Long>();
        List<String> roleCodeList = new ArrayList<String>();
        Set<String> permissions = new HashSet<String>();
        for (SysRoleUser roleUser : sysRoleUsers) {
            roleList.add(roleUser.getRoleId().longValue());
             SysRole role = sysRoleMapper.selectById(roleUser.getRoleId());
            roleCodeList.add(role.getNum()+"");
            //roleNameList.add(role.getName());
            permissions.addAll(sysRolePermissionMapper.selectByRoleId(roleUser.getRoleId().intValue()));
        }
        shiroUser.setRoleList(roleList);
        //shiroUser.setRoleName(roleNameList);
        shiroUser.setRoleCode(roleCodeList);
        shiroUser.setPermissions(permissions);

       // shiroUser.setUrls(resUrls);
        tokenCache.setUser(HttpUtil.getToken(), shiroUser);
        return shiroUser;
    }

    public SimpleAuthenticationInfo info(ShiroUser shiroUser, SysUser user, String realmName) {
        String credentials = user.getPwd();
        // 密码加盐处理
        String source = user.getSalt();
        ByteSource credentialsSalt = new Md5Hash(source);
        return new SimpleAuthenticationInfo(shiroUser,credentials, credentialsSalt, realmName);
    }

}

